let maximgsize = 100;
let Id = 0,
    type = 0;
//全局定义一次, 加载formSelects
layui.config({
    base: '../../js/layui/lay/modules/'
}).use(['form', 'laypage', 'layer', 'element', 'upload', 'table'], function() {
    form = layui.form;
    layer = layui.layer;
    upload = layui.upload; //上传
    table = layui.table;
    laypage = layui.laypage;
    element = layui.element; //元素操作
    Id = GetQueryString("Id");
    TypelistByTypeId(2);
    type = sessionStorage.getItem("type");
    if (!isNotNull(Id)) {
        Id = 0
        selectAllProductInfoByInfoPc();
    } else {
        let tempName = "";
        if (type == 38) { //茶文化
            tempName = "/getFindArticleById";
        } else if (type == 39) { //茶言说
            tempName = "/getFindSelectedkById";
        } else if (type == 40) { //茶精选
            tempName = "/getFindSelectedkById";
        }
        SelectActicleListById(tempName);
    };
    if (!isNotNull(type)) {
        layer.alert("未找到您的类型哟!请重新进入");
        layer.closeAll();
    }
    //上传图片
    var totalArray = new Array();
    var uploadInsts = upload.render({
        elem: '#uploadmultiple' //绑定元素
            ,
        url: httpurl + '/uploadImgQiniu?pathName=find&&divisor=0&dividend=1' //上传接口
            ,
        accept: 'images' // 允许上传的文件类型
            // , acceptMime: 'image/jpg,image/png'   // (只支持jpg和png格式，多个用逗号隔开),
            ,
        size: 5120 // 最大允许上传的文件大小  单位 KB
            //, auto: false //选择文件后不自动上传
            //, bindAction: '#startUpload' //指向一个按钮触发上传
            ,
        multiple: true // 开启多文件上传
            ,
        number: maximgsize //  同时上传文件的最大个数
            ,
        choose: function(obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            var arr = Object.keys(files);
            totalArray = totalArray.concat(arr);
            // 检查上传文件的个数
            if (totalArray.length > maximgsize) {
                // 超出上传最大文件
                layer.msg("上传文件最大不超过" + maximgsize + "个")
            }
        },
        done: function(res, index, upload) {
            if (res.rtnCode == 200) { //上传成功
                var nameurl = res.msg;
                var infos = '<li>' +
                    '<div class="pic_li_div pic_li_divimg">' +
                    '<img class="goods_img_list" src="' + visitimgurl + "/" + nameurl + '" >' +
                    '<div class="pic_btn" onclick="icon_remove(this)"><img src="../../img/close4.png" style="width: 16px;height: 16px;"></div>' +
                    '</div>' +
                    '</li>';
                $("#uploadmultiple").before(infos);
            }
            this.error(index, upload);
        },
        error: function() {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn  demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function() {
                uploadInsts.upload();
            });
        }
    });
    //上传视频
    var uploadInst = upload.render({
        elem: '#uploadvideo',
        url: httpurl + '/uploadImgQiniu?pathName=find&&divisor=0&dividend=1' //上传接口
            ,
        accept: 'video' //视频
            ,
        done: function(res) {
            if (res.rtnCode == 200) { //上传成功
                var nameurl = res.msg;
                var infos = '<li>' +
                    '<div class="pic_li_div videoInfo">' +
                    '<video src="' + visitimgurl + "/" + nameurl + '" controls="controls"></video>' +
                    '<div class="pic_btn" onclick="icon_remove(this)"><img src="../../img/close4.png" style="width: 16px;height: 16px;"></div>' +
                    '</div>' +
                    '</li>';
                $("#uploadvideo").before(infos);
            }
            if (res.rtnCode == 200) {
                $(".videoInfo video").attr("name", res.msg);
                $(".videoInfo").show();
                $(".videoInfo video").attr("src", visitimgurl + "/" + res.msg);
                layer.alert("上传成功", { offset: ['200px', '450px'], icon: 6 });
            }
        },
        error: function() {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function() {
                uploadInst.upload();
            });
        }
    });
    if (type == 38) {
        $(".typeNot38").hide();
    } else if (type == 39 || type == 40) {
        $(".typeNot39_40").hide();
    }
});

function SelectActicleListById(tempName) {
    $.ajax({
        url: httpurl + tempName,
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "id": Id,
        },
        success: function(data) {
            if (data.rtnCode == 200) {
                let dataInfo = data.data;
                if (type == 38) {
                    UE.getEditor('container').setContent(dataInfo.context); //商品描述
                    form.render();
                    $("#title").val(dataInfo.title);
                    // $("#sort").val(dataInfo.sort);
                    if (isNotNull(dataInfo.images))
                        select_img_list(dataInfo.images);
                } else if (type == 39 || type == 40) {
                    $('input:radio[name="state"][value="' + dataInfo.disable + '"]').attr('checked', 'true');
                    UE.getEditor('container').setContent(dataInfo.context);
                    form.render();
                    $("#title").val(dataInfo.title);
                    $("#sort").val(dataInfo.sort);
                    if (isNotNull(dataInfo.video)) {
                        select_vode_list(dataInfo.video);
                    }
                    if (isNotNull(dataInfo.image))
                        select_img_list(dataInfo.image);
                }

                if (isNotNull(dataInfo.pidjson)) listId = dataInfo.pidjson.split(",");
                selectAllProductInfoByInfoPc();
            }
        }
    })
}
//处理轮播图片
function select_img_list(imgList) {
    let infos = "";
    if (imgList.length > 0) {
        let imgArr = imgList.split(",");
        for (let i = 0; i < imgArr.length; i++) {
            infos += '<div class="pic_li_div pic_li_divimg">' +
                '<img class="goods_img_list" src="' + imgArr[i] + '" >' +
                '<div class="pic_btn" onclick="icon_remove(this)"><img src="../../img/close4.png" style="width: 16px;height: 16px;"></div>' +
                '</div>';
        }
    }
    $("#uploadmultiple").before(infos);
}
//处理多个图片
function select_vode_list(vodeList) {
    let infos = "";
    if (vodeList.length > 0) {
        let imgArr = vodeList.split(",");
        for (let i = 0; i < imgArr.length; i++) {
            infos += '<div class="pic_li_div videoInfo">' +
                '<video src="' + imgArr[i] + '" controls="controls"></video>' +
                '<div class="pic_btn" onclick="icon_remove(this)"><img src="../../img/close4.png" style="width: 16px;height: 16px;"></div>' +
                '</div>';
        }
        $("#uploadvideo").before(infos);
    }
}

function submitInfo() {
    let state = $("input[name='state']:checked").val();
    var title = $("#title").val();
    // var sort=$("#sort").val();
    let good_video_list = [];
    $(".good_video_list .pic_li_divimg").each(function() {
            good_video_list.push($(this).find("img").attr("src"));
        })
        //商品轮播图片
    let goods_img_list = [];
    $(".good_pic_list .pic_li_divimg").each(function() {
            goods_img_list.push($(this).find("img").attr("src"));
        })
        //选择的产品  判断只能选择一个
    if (listId.length < 0) {
        top.layer.alert("您还没有选择要推荐的商品哟!!");
        return;
    }
    let pro_content = UE.getEditor('container').getContent();
    if (pro_content == "") {
        top.layer.alert("请输入商品简介!");
        return;
    }
    let sort = $("#sort").val();
    sort = (sort == "" ? 0 : sort);
    top.layer.confirm('是否确定提交？', { icon: 3, title: '提示信息' }, function(index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        let tempHttp = "";
        let data = {};
        if (type == 39) { //茶言说
            // tempHttp=(Id==0?"insertFindInfoPc":"updeFindArticle");
            // data={"id": Id, "type": type, "img":goods_img_list, "pidjson":listId.join(","), "sort":sort, "vode_img":vode_img, "vode":vode, "disable":state, "context":context, "content":content};
        } else if (type == 40) { //茶精选
            tempHttp = (Id == 0 ? "increaseFindTeatalkPc" : "updFindSelected");
            data = { "id": Id, "type": type, "title": title, "context": pro_content, "image": goods_img_list.join(","), "pidjson": listId.join(","), "sort": sort, "video": good_video_list.join(","), "disable": state, "ftype": 1 };
        } else if (type == 38) { //茶文化
            tempHttp = (Id == 0 ? "insrFindArticle" : "updeFindArticle");
            data = { "id": Id, "type": type, "title": title, "context": pro_content, "images": goods_img_list.join(","), "pidjson": listId.join(","), "sort": sort };
        }
        setTimeout(function() {
            $.ajax({
                url: httpurl + "/" + tempHttp,
                cache: false,
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "*",
                    "Access-Control-Allow-Headers": "Authorization",
                    "Authorization": GetTokenInfo()
                },
                contentType: 'application/json',
                data: data,
                success: function(data) {
                    closeAllLayer();
                    top.layer.confirm(data.msg, { icon: 3, title: '提示信息' }, function(index) {
                        return_list();
                    }, function() {

                    });
                }
            });
        }, 1000);
    })
}
//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的  是 ID,不用加 # 号
            ,
        count: totalRecords //数据总数，从服务端得到
            ,
        layout: ['count', 'prev', 'page', 'next', 'refresh', 'skip'],
        curr: pageNo //获取hash值为fenye的当前页
            ,
        hash: 'fenye' //自定义hash值
            ,
        limit: pageSize,
        jump: function(obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr; // 当前页数;
                pageSize = obj.limit; // 当前页面记录数
                selectAllProductInfoByInfoPc();
            }
        }
    });
}